let config = require('../config/config.js')
const host = config.request_url

/**
 * 封装uni.request请求
 * @param {String} url 请求接口地址
 * @param {String} method 请求方式
 * @param {Object} data 请求参数
 * @param {Number} headerType 请求头类型
 * @param {Boolean} isLoading 是否显示loading
 */
function http(url, method, data, headerType, isLoading, timeout) {
	var header = {
		'content-type': 'application/x-www-form-urlencoded'
	}
	var timeout = timeout ? timeout : 20000
	if (typeof headerType === 'boolean') {
		var isLoading = headerType
		var headerType = null
	}
	if (typeof data !== 'object') {
		var isLoading = headerType
		var headerType = data
		var data = {}
	}
	if (headerType === 0) {
		header = {
			'content-type': 'application/json'
		}
	}
	if (headerType === 1) {
		header = {
			'content-type': 'application/x-www-form-urlencoded'
		}
	}
	if (method === 'GET') {
		header = {}
	}
	if (uni.getStorageSync('dwu_token')) {
		header['token'] = uni.getStorageSync('dwu_token')
	}
	if (isLoading !== false) {
		uni.showLoading({
			title: '加载中...'
		})
	}
	return new Promise((resolve, reject) => {
		let requestTask = uni.request({
			method: method,
			url: host + url,
			data: data,
			header: header,
			timeout: timeout,
			success: (res) => {
				if (res.statusCode == 500) {
					uni.showToast({
						title: '您的网络不给力，请稍后重试',
						icon: 'none',
						duration: 3000
					})
					return
				}
				if (res.data.code != 1) {
					if (res.data.code == 401) {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 3000,
							success: () => {
								//获取当前页面栈的实例
								let pages = getCurrentPages();
								//获取当前页面
								let currentPage = pages[pages.length - 1];
								console.log(currentPage);
								let url = currentPage.route;
								let options = currentPage.options;
								let fullPath = currentPage.$page.fullPath;
								uni.setStorageSync('redirect_path', fullPath)
								uni.reLaunch({
									url: '/pages/login/login'
								})
							}
						})
						return
					}
					console.log(url);
					if (url == '/index/cityIfOn') {
						uni.hideLoading()
					} else if (url == '/user/masterWorkerCheckDetail') {
						uni.hideLoading()
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 3000
						})

					}
					reject(res)
					return
				}
				resolve(res)
				uni.hideLoading()
			},
			fail: (err) => {
				console.log(err);
				if (isLoading !== false) {
					uni.hideLoading()
				}
				if (err.errMsg == "request:fail timeout") {
					uni.showToast({
						title: '您的网络不给力，请稍后重试',
						icon: 'none',
						duration: 3000
					})
				}
				uni.hideLoading()
				reject(err)
			},
		})
	})
}

// 导出http方法
module.exports = {
	http
}